<?php
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\wework\listener;
use think\facade\Db;
use app\wework\model\CallbackModel;
use app\wework\model\QyWechatApi;

class ChangeExternalChat
{
    /**
     *自动拉群群回调
     */
    public function handle($event){
        $CorpID = $event['ToUserName'];
        $config = Db::table("kt_wework_config")->where(['corp_id'=>$CorpID])->find();
        $wid = $config["wid"];
        $group = Db::table("kt_wework_group")->where(["chat_id"=>$event["ChatId"],"wid"=>$wid])->find();
        $auto = Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"group_id"=>$group["id"],"status"=>1])->find();
        if(!$auto)return "不是该渠道";
        $count = Db::table("kt_wework_group_member")->where(["chat_id"=>$event["ChatId"],"wid"=>$wid,"status"=>1])->count();
        if($auto["size"] <= $count){
            Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"group_id"=>$group["id"],"status"=>1])->update(["status"=>3]);
            $next = Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"pid"=>$auto["pid"],"status"=>2,"orders"=>$auto["orders"]+1])->find();
            if($next)Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"pid"=>$auto["pid"],"status"=>2,"orders"=>$auto["orders"]+1])->update(["status"=>1]);
        }

        return true;
    }
}